﻿using System;
using System.Collections.Generic;
using System.Text;
using QTPlugin;
using Kawanon.QtHoney;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Kawanon.Sessions
{
	[Serializable]
	public class Session
	{
		public string Title { get; set; }
		public byte[][] Folders { get; set; }

		public Session(string title, ITab[] tabs)
		{
			Title = title;
			Folders = Array.ConvertAll(tabs, delegate(ITab tab)
			{
				Address addr = tab.Address;
				return Utility.PidlFromAddress(addr);
			});
		}

		public override string ToString()
		{
			return Title;
		}
	}

	public static class SessionManager
	{
		public static SessionManagerInformation Information { get; set; }

		static SessionManager()
		{
			Information = new SessionManagerInformation();
		}

		public static void Open(IPluginServer server, Session s)
		{
			Address[] addrs = Array.ConvertAll(s.Folders, delegate(byte[] bytes)
			{
				//IntPtr pidl = Marshal.AllocCoTaskMem(bytes.Length);
				//Marshal.Copy(bytes, 0, pidl, bytes.Length);
				//Address addr = new Address(pidl);
				//Marshal.FreeCoTaskMem(pidl);
				return new Address(bytes, null);
			});

			int index = (server.SelectedTab != null) ? server.SelectedTab.Index + 1 : 0;
			for (int i = 0; i < addrs.Length; i++)
			{
				// エラー対策 検索結果などを渡すとエラーとなる
				if (Utility.AddressToPath(addrs[i]) != null)
				{
					server.CreateTab(addrs[i], i + index, false, i == 0);
				}
				//Application.DoEvents();
			}
		}

		public static bool Remove(Session s)
		{
			List<Session> list = new List<Session>(SessionManager.Load());
			int index = list.FindIndex(delegate(Session session)
			{
				return session.Title == s.Title;
			});
			if (index == -1)
			{
				return false;
			}
			list.RemoveAt(index);
			SessionManager.Save(list);
			return true;
		}

		public static IEnumerable<Session> Load()
		{
			Stream stream = Persistence.CreateValueStream("Sessions");
			if (stream == null)
			{
				return new List<Session>();
			}
			return Persistence.UnpackArchive<Session>(stream);
		}

		public static void Save(IEnumerable<Session> e)
		{
			Persistence.SaveBinary("Sessions", Persistence.CreateArchive(e));
		}
	}

	public class SessionManagerInformation
	{
		//public bool Enabled { get; set; }
	}
}
